/**
 *
 * @description:
 * @author: junyong.hong
 * @createTime: 2018/10/9
 * @version: 1.0.0.0
 * @history:
 *    1、
 *    2、
 *
 */
const Koa = require('koa')
const { resolve } = require('path')
const bodyParser = require('koa-bodyparser')
const session = require('koa-session')
const serve = require('koa-static')
const mongoose = require('mongoose')
const moment = require('moment')
const Router = require('koa-router')
// const wechat = require('./wechat-lib/middleware')
const config = require('./config/config')
// const { reply } = require('./wechat/reply')
const { initSchemas, connect } = require('./app/database/init')


;(async () => {
    await connect(config.db)

    initSchemas()

    // const { test } = require('./wechat/index')
    // // 测试token的数据库存储
    // await test()

    // 生成服务器实例
    const app = new Koa()
    const router = new Router()

    // 引用koa-views，接入pug
    const views = require('koa-views')
    app.use(views(resolve(__dirname, 'app/views'), {
        extension: 'pug',
        options: {
            // 日期（在所有的pug页面上都可以使用）
            moment: moment
        }
    }))

    app.keys = ['imooc']
    app.use(session(app))
    app.use(bodyParser())
    app.use(serve(resolve(__dirname, '../public')))

    // 植入两个中间件，做前置的微信环境检查、跳转、回调的用户数据存储和状态同步
    const wechatController = require('./app/controllers/wechat.controller')

    app.use(wechatController.checkWechat)
    app.use(wechatController.wechatRedirect)

    app.use(async (ctx, next) => {
        const User = mongoose.model('User')
        let user = ctx.session.user

        // 如果session，去数据库里查找对应的昵称
        if (user && user._id) {
            user = await User.findOne({ _id: user._id })

            ctx.session.user = {
                _id: user._id,
                role: user.role,
                nickname: user.nickname
            }


            ctx.state = Object.assign(ctx.state, {
                user: {
                    _id: user._id,
                    nickname: user.nickname
                }
            })

            // { user: { _id: 5c6f4450954aa62448cbf504, nickname: 'haha' } }
        } else {
            ctx.session.user = null
        }

        await next()
    })


    require('./config/routes')(router)
    app.use(router.routes()).use(router.allowedMethods())
    // 接入微信消息中间件
    // require('./config/')

    // 加载认证的中间件（被路由接管）
    // app.use(wechat(config.wechat, reply))

    app.listen(config.port)
    console.log('listen:' + config.port)
})()

